import axios from "axios";
import {useLoginStore} from "@/store/index.js";
import {serverAddress} from "@/config/Config.js";
import {ElMessage, ElNotification} from "element-plus";

const request =axios.create({
    timeout:3000,
    baseURL:serverAddress()
})

request.interceptors.request.use((config) => {
    config.headers['from'] = "admin"
    let accessToken = sessionStorage.getItem("accessToken")
    if (accessToken){
        config.headers['accessToken'] = accessToken
    }
    return config;
});


request.interceptors.response.use((response) => {
    const {closeLoginLoading} = useLoginStore()
   closeLoginLoading()
    if (response.data.code!==20000){
        ElMessage.error(response.data.message)
        return Promise.reject(new Error(response.data.message))
    }

    return response.data

},((error)=>{
    const {closeLoginLoading} = useLoginStore()
    closeLoginLoading()
    ElNotification({
        title: '服务异常',
        message: error.message,
        type: 'error',
    })
    return Promise.reject(error)
}));

export default request;